package com.yongninger.activity.product;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.yongninger.activity.R;
import com.yongninger.dao.ProductDao;
import com.yongninger.vo.ProductVo;

public class AddActivity extends Activity {
	private ProductDao productDao;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.product_add);
		productDao = new ProductDao(getApplicationContext());
		Button addBtn = (Button) this.findViewById(R.id.add);
		OnClickListener onClickListener = new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// 保存数据到数据库
				if (save()) {
					Toast.makeText(getApplicationContext(), "保存成功", 2).show();
					// 跳转到查询页面
					Intent intent = new Intent(AddActivity.this,
							ListActivity.class);
					startActivity(intent);
				} else {
					Toast.makeText(getApplicationContext(), "保存失败", 2).show();
				}
			}
		};
		addBtn.setOnClickListener(onClickListener);
	}

	private boolean save() {
		EditText pname = (EditText) findViewById(R.id.pname);
		EditText pcode = (EditText) findViewById(R.id.pcode);
		EditText pcategory = (EditText) findViewById(R.id.pcategory);
		EditText ptype = (EditText) findViewById(R.id.ptype);
		EditText smeasure1 = (EditText) findViewById(R.id.smeasure1);
		EditText smeasure2 = (EditText) findViewById(R.id.smeasure2);
		EditText pprice = (EditText) findViewById(R.id.pprice);
		ProductVo productVo = new ProductVo();
		productVo.setPcategory(pcategory.getText().toString());
		productVo.setPcode(pcode.getText().toString());
		productVo.setPname(pname.getText().toString());
		productVo.setPprice(pprice.getText().toString());
		productVo.setPtype(ptype.getText().toString());
		productVo.setSmeasure1(smeasure1.getText().toString());
		productVo.setSmeasure2(smeasure2.getText().toString());
		return productDao.insertProductVo(productVo);
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			Toast.makeText(getApplicationContext(), "请先保存内容",
					Toast.LENGTH_SHORT).show();
			return false;
		}else if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() >= 0){
			finish();
			// 跳转到查询页面
			Intent intent = new Intent(AddActivity.this,
					ListActivity.class);
			startActivity(intent);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
